package com.tfswx.jcyw.ruleenginedesigner.util;

import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.jcyw.ruleenginedesigner.dao.model.GzyqXtYh;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Ricky
 * @date 2021/4/16
 */
@Slf4j
public class UserManger {
    private static final String ACCESS_TOKEN = "access_token";

    private UserManger() {
    }

    public static String getLoginRybm() {
        return getLoginUserInfo().getRybm();
    }

    public static UserInfo getLoginUserInfo() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new AppException("未获取到请求对象");
        }
        HttpServletRequest request = attributes.getRequest();

        return getLoginUserInfo(request);
    }

    public static UserInfo getLoginUserInfo(HttpServletRequest request) {
        String accessToken = request.getHeader(ACCESS_TOKEN);
        if (StringUtils.isEmpty(accessToken)) {
            throw new AppException("未登录或登录已过期");
        }

        UserInfo userInfo = JwtUtil.getUserInfo(accessToken, UserInfo.class);

        if (userInfo == null || StringUtils.isEmpty(userInfo.getRybm())) {
            throw new AppException("未登录或登录已过期");
        }
        return userInfo;
    }

    public static UserInfo toUserInfo(GzyqXtYh gzyqXtYh) {
        UserInfo userInfo = new UserInfo();
        userInfo.setRybm(gzyqXtYh.getRybm());
        userInfo.setMc(gzyqXtYh.getMc());
        userInfo.setDlbm(gzyqXtYh.getDlbm());
        return userInfo;
    }


    @Data
    public static class UserInfo {
        @ApiModelProperty(example = "9800000053")
        private String rybm;
        @ApiModelProperty(example = "测试账户0202")
        private String mc;
        @ApiModelProperty(example = "test0202")
        private String dlbm;
    }
}
